import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository, Not, IsNull } from 'typeorm'
import { CreateRoleDto } from './dto/create-role.dto'
import { UpdateRoleDto } from './dto/update-role.dto'
import { Role } from './entities/role.entity'
import { formatOptionData } from 'src/utils'
@Injectable()
export class RoleService {
  constructor(
    @InjectRepository(Role) private readonly role: Repository<Role>
  ) {}
  create(createRoleDto: CreateRoleDto) {
    const role = new Role()
    role.name = createRoleDto.name
    role.desc = createRoleDto.desc
    return this.role.save(role)
  }

  async findAll(params: {
    page: number
    pageSize: number
    isDelete?: boolean
  }) {
    const where = {}
    params.isDelete && (where['deleteDate'] = Not(IsNull()))
    const data = await this.role.find({
      where: { ...where },
      withDeleted: params.isDelete,
      skip: (params.page - 1) * params.pageSize,
      take: params.pageSize
    })
    const total = await this.role.count({
      where: { ...where },
      withDeleted: params.isDelete
    })
    return { data, total }
  }

  async findAllOption() {
    const data = await this.role.find()
    return formatOptionData(data)
  }

  async findOne(id: number) {
    return await this.role.findOne({ where: { id } })
  }

  update(id: number, updateRoleDto: UpdateRoleDto) {
    return this.role.update(id, updateRoleDto)
  }

  remove(ids: number[]) {
    return this.role.softDelete(ids)
  }

  thoroughRemove(ids: number[]) {
    return this.role.delete(ids)
  }

  restore(ids: number[]) {
    return this.role.restore(ids)
  }
}
